package com.gdpu.pbss.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.gdpu.pbss.Constants.Constants;
import com.gdpu.pbss.exception.ServiceException;
import com.gdpu.pbss.pojo.Manager;
import com.gdpu.pbss.pojo.User;
import com.gdpu.pbss.service.ManagerService;
import com.gdpu.pbss.service.UserService;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String  token=request.getHeader("utoken");


        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        if (StrUtil.isBlank(token)){
            throw new ServiceException(Constants.CODE_401,"无token,请重新登录");
        }
        Integer userId;
        try {
            userId= Integer.valueOf(JWT.decode(token).getAudience().get(0));
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_401,"token验证失败");
        }

        User user= userService.getById(userId);
        if (user==null){
            throw new ServiceException(Constants.CODE_401,"用户不存在");
        }

        //用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassward())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constants.CODE_401, "token验证失败，请重新登录");
        }
        return true;
    }
}